﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using UwaySoft.EsheetServer.BizLogic;
using UwaySoft.EsheetServer.DataLayer;
using UwaySoft.EsheetServer.Help.Response;
using UwaySoft.EsheetServer.Help.Template;

namespace UwaySoft.EsheetServer.Help
{
    public class SendSmsWebService
    {
        private SendSmsWebService()
        {

        }

        protected ISqlHelper SqlHelper
        {
            get { return Application.SqlHelper; }
        }


        private static SendSmsWebService m_SendSmsWebService = null;
        public static SendSmsWebService Instance()
        {
            if (m_SendSmsWebService == null)
                m_SendSmsWebService = new SendSmsWebService();

            if (WebServiceType == null || WebServiceObj == null) { } InitWebService();

            return m_SendSmsWebService;
        }

        #region WebService实例化对象
        /// <summary>
        /// WebService实例化对象
        /// </summary>
        private static Type WebServiceType = null;
        /// <summary>
        /// WebService实例化对象
        /// </summary>
        private static object WebServiceObj = null;
        #endregion

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        private static void InitWebService()
        {
            try
            {
                string SendSmsURL = ConfigurationSettings.AppSettings["SENDSMSURL"].ToString().Trim();
                System.Net.WebClient wc = new System.Net.WebClient();
                System.IO.Stream stream = wc.OpenRead(SendSmsURL + "?WSDL");
                System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream);
                System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                //System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace);
                System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace();
                System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler();

                System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
                System.Reflection.Assembly assembly = cr.CompiledAssembly;

                WebServiceType = assembly.GetType("SmcServiceService", true, true);
                WebServiceObj = Activator.CreateInstance(WebServiceType);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
        #endregion

        #region 发送告警短信
        /// <summary>
        /// 告警信息回馈发送短信
        /// </summary>
        /// <param name="BelongsID"></param>
        /// <param name="BelongsCode"></param>
        /// <param name="MergeCount"></param>
        /// <param name="nBusCode">业务编号</param>
        /// <param name="nStrategyID"></param>
        /// <param name="nStrategyType">1短信 2邮件</param>
        /// <param name="useinfo"></param>
        /// <param name="SmsContent"></param>
        /// <param name="SendTime"></param>
        public void Deliver(string nBusCode, string toUser, string SmsContent, DateTime SendTime, string BelongsID, string keyid)
        {

            string UserName = ConfigurationSettings.AppSettings["SENDSMS_USERNAME"].ToString().Trim();
            string PassWord = ConfigurationSettings.AppSettings["SENDSMS_PASSWORD"].ToString().Trim();
            object objReturnValue = null;
            try
            {
                if (WebServiceObj == null)
                    InitWebService();
                lock (WebServiceObj)
                {
                    System.Reflection.MethodInfo mi = WebServiceType.GetMethod("deliver");

                    objReturnValue = mi.Invoke(WebServiceObj, new object[] { UserName, PassWord, 2, Convert.ToInt32(nBusCode), 2, toUser, 1, SmsContent, SendTime.ToString("yyyy-MM-dd HH:mm:ss") });
                    if (objReturnValue != null)
                    {
                        SqlHelper.ExecuteNonQuery(string.Format(@" insert into mod_sms_preparesend (id,username,pwd,type,src_id,smslevel,to_users,send_way,content,send_time,curtime,issucceed,BELONGSID,keyid) values (seq_mod_sms_preparesend.nextval,'{0}','{1}',2,'{2}',2,'{3}',{4},'{5}',to_char(sysdate,'YYYY-MM-DD HH24:MI:SS'),sysdate,{6},{7},'{8}') ", UserName, PassWord, nBusCode, toUser, "''", SmsContent, objReturnValue, BelongsID, keyid));
                    }
                }
            }
            catch (Exception Err)
            {
                SqlHelper.ExecuteNonQuery(string.Format(@" insert into mod_sms_preparesend (id,username,pwd,type,src_id,smslevel,to_users,send_way,content,send_time,curtime,issucceed,BELONGSID,keyid) values (seq_mod_sms_preparesend.nextval,'{0}','{1}',2,'{2}',2,'{3}',{4},'{5}',to_char(sysdate,'YYYY-MM-DD HH24:MI:SS'),sysdate,{6},{7},'{8}') ", UserName, PassWord, nBusCode, toUser, "''", SmsContent, "-99999", BelongsID, keyid));
            }

        }


        #endregion

        #region KPI发送短信
        /// <summary>
        /// KPI发送短信
        /// </summary>
        /// <param name="nBusCode">业务编号</param>
        /// <param name="nStrategyType">1短信 2邮件</param>
        /// <param name="PhoneList">电话号码</param>
        /// <param name="SmsContent">短信内容</param>
        /// <param name="SendTime">发送时间（为空则立即发送）</param>
        public void DeliverKpi(int nBusCode, int nStrategyType, string PhoneList, string SmsContent, DateTime SendTime)
        {
            string strPhoneList = PhoneList;
            string strEmailList = "";


            if (strPhoneList.Length >= 1 || strEmailList.Length >= 1)
            {
                string UserName = ConfigurationSettings.AppSettings["SENDSMS_USERNAME"].ToString().Trim();
                string PassWord = ConfigurationSettings.AppSettings["SENDSMS_PASSWORD"].ToString().Trim();
                try
                {
                    if (WebServiceObj == null)
                        InitWebService();
                    lock (WebServiceObj)
                    {
                        System.Reflection.MethodInfo mi = WebServiceType.GetMethod("deliver");
                        object objReturnValue = mi.Invoke(WebServiceObj, new object[] { UserName, PassWord, 2, nBusCode, 2, string.Format("<PHONE>{0}</PHONE><EMAIL>{1}</EMAIL>", strPhoneList, strEmailList), nStrategyType, SmsContent, SendTime.ToString("yyyy-MM-dd HH:mm:ss") });

                        SqlHelper.ExecuteNonQuery(string.Format(@" insert into mod_sms_preparesend (id,username,pwd,type,src_id,smslevel,to_users,send_way,content,send_time,curtime,issucceed) 
                      values (seq_mod_sms_preparesend.nextval,'{0}','{1}',2,'{2}',2,'{3}',{4},'{5}','{6}',sysdate,{7}) ",
                                               UserName, PassWord, nBusCode, string.Format("<PHONE>{0}</PHONE><EMAIL>{1}</EMAIL>", strPhoneList, strEmailList), nStrategyType, SmsContent, SendTime.ToString("yyyy-MM-dd HH:mm:ss"), objReturnValue));
                    }
                }
                catch
                {
                    SqlHelper.ExecuteNonQuery(string.Format(@" insert into mod_sms_preparesend (id,username,pwd,type,src_id,smslevel,to_users,send_way,content,send_time,curtime,issucceed) 
                      values (seq_mod_sms_preparesend.nextval,'{0}','{1}',2,'{2}',2,'{3}',{4},'{5}','{6}',sysdate,-999999) ",
                                          UserName, PassWord, nBusCode, string.Format("<PHONE>{0}</PHONE><EMAIL>{1}</EMAIL>", strPhoneList, strEmailList), nStrategyType, SmsContent, SendTime.ToString("yyyy-MM-dd HH:mm:ss")));
                }
            }
        }
        #endregion
    }
}
